import { defineConfig } from 'vite'
import path from 'node:path'
import react from '@vitejs/plugin-react-swc'
import tailwindcss from '@tailwindcss/vite'
import { vitePluginFakeServer } from 'vite-plugin-fake-server'

export default defineConfig(({ command }) => {
	const root = process.cwd()
	const isBuild = command === 'build'
	return {
		root,
		plugins: [
			react(),
			tailwindcss(),
			vitePluginFakeServer({
				include: 'mock',
				enableDev: true,
				enableProd: true,
				logger: false,
			}),
		],
		resolve: {
			alias: {
				'@': path.resolve(__dirname, 'src'),
			},
		},
		server: {
			host: true,
			port: 3000,
		},
		build: {
			rollupOptions: {
				output: {
					assetFileNames: 'assets/[ext]/[name]-[hash].[ext]',
					entryFileNames: 'assets/js/[name]-[hash].js',
					// js分包优化
					// https://rollup.nodejs.cn/configuration-options/#output-manualchunks
					manualChunks(id) {
						const otherChunks = ['lodash', 'tailwindcss', 'echarts']
						if (
							otherChunks.find((chunk) => id.includes(`node_modules/${chunk}/`))
						) {
							return id
								.toString()
								.split('node_modules/')[1]
								.split('/')[0]
								.toString()
						}
					},
					chunkFileNames: (chunkInfo) => {
						const facadeModuleId = chunkInfo.facadeModuleId
							? chunkInfo.facadeModuleId.split('/')
							: []
						const fileName =
							facadeModuleId[facadeModuleId.length - 2] || '[name]'
						return `assets/js/${fileName}/[name].[hash].js`
					},
				},
			},
			target: 'es2015',
		},
		esbuild: {
			drop: isBuild ? ['debugger', 'console'] : [],
			legalComments: 'none',
		},
	}
})
